import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { auth } from './auth'

// 根据环境变量确定API基础URL
const getBaseURL = () => {
  try {
    const config = useRuntimeConfig()
    const buildEnv = config.public.buildEnv
    
    // 根据不同的环境返回不同的API基础URL
    switch (buildEnv) {
      case 'test':
        return 'https://test.mletter.cn'
      case 'production':
        return 'https://api.example.com'
      default:
        return config.public.apiBase || 'http://localhost:9800'
    }
  } catch (error) {
    // 当在静态生成时无法访问Nuxt实例，返回默认API地址
    return process.env.NUXT_PUBLIC_API_BASE || 'http://localhost:9800'
  }
}

export { getBaseURL }
interface ApiResponse<T = any> {
  code: number
  data: T
  msg: string
  tracers: string
}

class Api {
  private instance: AxiosInstance

  constructor() {
    this.instance = axios.create({
      baseURL: getBaseURL(),
      timeout: 10000
    })

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = auth.getToken()
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        const data = response.data
        if (data.code !== 0) {
          // 使用Nuxt的useToast显示错误信息
          const toast = useToast()
          console.log(data.msg.split(';')[0])
          toast.add({
            title: '提示',
            description: data.msg || '操作失败',
            color: 'red',
            icon: 'i-heroicons-exclamation-circle',
            timeout: 3000
          })
        }
        return data
      },
      async (error) => {
        if (error.response?.status === 401) {
          // 清除本地存储的token和用户信息
          localStorage.removeItem('token')
          localStorage.removeItem('username')
          localStorage.removeItem('user_id')
          // 跳转到登录页
          window.location.href = '/user/login'
        } else {
          // 显示错误提示
          const toast = useToast()
          const errorData = error.response?.data
          toast.add({
            title: '错误',
            description: (errorData && errorData.msg) || error.message || '网络请求失败',
            color: 'red',
            icon: 'i-heroicons-exclamation-circle',
            timeout: 3000
          })
        }
        return Promise.reject(error)
      }
    )
  }

  async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    return this.instance.get(url, config)
  }

  async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    return this.instance.post(url, data, config)
  }

  async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    return this.instance.put(url, data, config)
  }

  async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    return this.instance.delete(url, config)
  }
}

export const api = new Api()